import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent, AlertOptions, BadgePipe, deepCopy, MessageService, ModalComponent, paginationFactory, PaginationService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {HttpClient, HttpParams} from '@angular/common/http';
import {ChargeRecordFormatterService} from '../../../../services/formatter/charge-record-formatter.service';
import {Router} from '@angular/router';
import {MoneyRecordFormatterService} from '../../../../services/formatter/money-record-formatter.service';
const paginationProvider = {
  provide: PaginationService,
  useFactory: paginationFactory,
  deps: [HttpClient, TicketService]
};
@Component({
  selector: 'money-manager',
  templateUrl: './money-manager.component.html',
  styleUrls: ['./money-manager.component.scss'],
  providers: [ChargeRecordFormatterService, BadgePipe, paginationProvider]
})
export class MoneyManagerComponent implements OnInit, AfterViewInit {
  @ViewChild('modal') modal: ModalComponent;
    breadcrumb = [
        {name: '提现管理', cssIcon: 'fa fa-fw fa-credit-card'}
    ];
  @ViewChild('alert') alert: AlertComponent;
  alertOptions: AlertOptions = {
    theme: 'danger',
    data: null,
    position: 'center'
  };
  handleData;
  page = 1;
  moneyTable = new Table({
      headers: this.moneyFormatter.formatter,
      buttons: [
          {
              btnClass: 'btn-success p-1',
              text: '确认',
              isShow: true,
              click: (e) => {
                this.showConfirmModal(e);
              }
          },
        {
          btnClass: 'btn-danger p-1',
          text: '取消',
          isShow: true,
          click: (e) => {
            this.showCancelModal(e);
          }
        },
      ]
  });

    constructor(private message: MessageService,
                private ticketService: TicketService,
                public pagination: PaginationService,
                private router: Router,
                private moneyFormatter: MoneyRecordFormatterService) {
    }
    ngOnInit() {
        this.getInfo(1);
    }
  showConfirmModal(item: any) {
    const options = {
      id: 'confirmItem',
      title: '处理订单',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否审核通过该订单？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.handleData = item;
  }
  showCancelModal(item: any) {
    const options = {
      id: 'cancelItem',
      title: '处理订单',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否取消该订单？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.handleData = item;
  }
  handleItem(status: number) {
    this.ticketService.post(this.ticketService.urls.dealOrder, {id: this.handleData.id, status: status}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
      if (resp.body.success) {
        this.getInfo(this.page);
      } else {
        this.alertOptions.data = resp.body.msg;
        this.alert.show(this.alertOptions, 2000);
      }
    });
  }
  getInfo(page) {
    this.pagination.simpleFormatter = this.moneyTable.options.headers;
    this.ticketService.get(this.ticketService.urls.getOrderList, {
      observe: 'response',
      params: new HttpParams()
        .append('web_token', localStorage.getItem('token'))
        .append('orderType', '2')
        .append('pageNum', page + '')
        .append('pageSize', '10')
        .append('status', '0')}).subscribe((resp) => {
          if (resp.body.success) {
            const result = resp.body.returnValue.page;
            const resultData = [];
            for (const item of result.list) {
              const curItem = deepCopy(item);
              if (item.toType === 1) {
                curItem.type_display = '银行';
              } else {
                curItem.type_display = '平台';
              }
              resultData.push(curItem);
            }
            this.pagination.page.results = resultData;
            this.pagination.page.totalPage = result.pages;
            this.pagination.page.pageNumber = result.pageNum;
            this.pagination.page.pageSize = result.pageSize;
            this.pagination.formatData();
            /** 绑定事件 */
            this.pagination.dataLoadSubscriber$.subscribe(() => {
              this.message.sendMessage('page load progress', this);
            });
          } else {
            this.router.navigateByUrl('/login').catch();
          }
    });
  }
  firstPage() {
      this.page = 1;
    this.getInfo(1);
  }
  previousPage() {
    if (this.page > 1) {
      this.page = this.page - 1;
    } else {
      this.page = 1;
    }
    this.getInfo(this.page);
  }
  nextPage() {
    if (this.page < this.pagination.page.totalPage) {
      this.page = this.page + 1;
    } else {
      this.page = this.pagination.page.totalPage;
    }
    this.getInfo(this.page);
  }
  lastPage() {
      this.page = this.pagination.page.totalPage;
    this.getInfo(this.pagination.page.totalPage);
  }
  ngAfterViewInit(): void {
    this.modal.event.subscribe({
      next: (event) => {
        if (event.name === 'confirm' && event.id === 'confirmItem') {
          this.modal.hide();
          this.handleItem(1);
        }
        if (event.name === 'confirm' && event.id === 'cancelItem') {
          this.modal.hide();
          this.handleItem(2);
        }
      }
    });
    this.message.sendMessage('page load progress', this, '300ms');
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
  }
}
